<html>
<head>
    <title>mockapi</title>
    <link rel='stylesheet' href='/stylesheets/bootstrap.min.css' />
    <link rel="stylesheet" href="/stylesheets/bootstrap-theme.min.css" >
    <link rel="stylesheet" href="/stylesheets/jquery.json-viewer.css" >
    <meta charset="utf-8">
    <style type="text/css">
        .th_item {
            width: 30px;
        }
        .th_10 {
            width: 10%;
            min-width: 50px;
        }
        .th_20 {
            width: 20%;
            min-width: 50px;
        }
        .th_short {
            width: 20%;
            min-width: 50px;
        }
        .th_long {
            width: 65%;
            min-width: 50px;
        }
        .th_taskid {
            width: 100px;
        }
        .json-renderer{
            margin-top: 5px;
        }
        .th_search {
            width: 15%;
            height: 30px;
        }
        .th_search .th_search_btn {
            width: 60px;
            height: 30px;
        }
        button {outline: 0px solid #ccc; width: 60px;margin-top: 2px;}
        pre {outline: 0px solid #ccc;margin-top: 5px; }
        code {outline: 0px solid #ccc;margin-top: 5px; }
        .string { color: green; }
        .number { color: rgb(85, 78, 69); }
        .boolean { color: blue; }
        .null { color: magenta; }
        .key { color: red; }
        #taskid_search{
            max-width: 200px;
            margin-top: 2px;
            color: rgb(85, 78, 69);
        }
        pre#json-renderer-96 {
            border: 1px solid #aaa;
        }
    </style>
</head>
<body>
<div class="panel panel-info">
        <div class="panel-heading">
            <h1 class="panel-title">模拟接口编辑页面</h1>
        </div>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title" id="myModalLabel">编辑数据</h4>
            </div>
              <div class="form-group">
                <input id="edit-body1" type="text" class="form-control" placeholder="taskid(任务单号)">
              </div>
              <div class="form-group">
                <input id="edit-body2" type="text" class="form-control" placeholder="reqid(文档请求id)">
              </div>
              <div class="form-group">
                <textarea class="form-control" rows="20" id="edit-body4" placeholder="出参(必须json格式)"></textarea>
              </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="editMock()">提交</button>
            </div>
        </div>
    </div>
</div>

<!-- 模态框（Modal） -->
<div class="modal fade" id="myModal-delete" tabindex="0" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title" id="myModalLabel">确认删除?</h4>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="delMockApi()">确认</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>
<!-- /.modal -->

<div >
      <form class="navbar-form navbar-left" role="search">
         <div style="width: 120px;" class="form-group">
            <div class="dropdown">
                <button style="width: 120px;" type="button" class="btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">A
                    <span class="caret"></span>
                </button>
                <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
                    <li role="presentation">
                        <a onclick="selectApp('02')" role="menuitem" tabindex="02">A</a>
                    </li>
                    <li role="presentation">
                        <a onclick="selectApp('06')" role="menuitem" tabindex="06" >B</a>
                    </li>
                    <li role="presentation">
                        <a onclick="selectApp('05')" role="menuitem" tabindex="05" >C</a>
                    </li>
                </ul>
            </div>
          </div>
          <div class="form-group">
            <input id="body1" type="text" class="form-control" placeholder="taskid(任务单号)">
          </div>
          <div class="form-group">
            <input id="body2" type="text" class="form-control" placeholder="reqid(文档请求id)">
          </div>
          <div class="form-group">
            <textarea style="width: 1000px;" class="form-control" rows="3" id="body4" placeholder="出参(必须json格式)"></textarea>
          </div>
        <button  type="button" class="btn btn-primary" onclick="addMockApi()">提交</button>
      </form>
</div>

<table class="table table-condensed">
    <thead>
        <tr>
            <th class="th_item">操作</th>
            <th class="th_10">app</th>
            <th class="th_10">
                <div  class="input-group input-group-sm ">
					<input placeholder="输入想查询的任务单号" id="taskid_search" type="text" class="form-control">
					<button id="task_search_btn" onclick="taskSearchQuery()" class="btn btn-default btn-sm th_search_btn" type="button" >
                        筛选
                    </button>
				</div>
            </th>
            <th class="th_short">模拟路径</th>
            <th class="th_long">出参</th>
        </tr>
    </thead>
    <tbody id="mockhistory">
    </tbody>
</table>

</body>
<script src="/javascripts/jquery.js"></script>
<script src="/javascripts/bootstrap.min.js"></script>
<script src="/javascripts/jquery.json-viewer.js"></script>
<script>
     /*
      *各种全局对象
      */

      //创建模拟数据时选择的app类型
      var _app = '02';

      //搜索时的任务单号
      var _taskid = '';

      //选中的编辑对象
      var _editInfo = {}

      //页面初始化
      $(document).ready(function(){
        var  mockhistory =  $('#mockhistory')
        mockhistory.empty() 
        getAllMockApis()
      }); 
      //app类型选择
      function selectApp(appid){
        _app = appid
        if(appid=='02'){
            $('#dropdownMenu1').text('A')
        }else if(appid=='05'){
            $('#dropdownMenu1').text('B')
        }else if(appid=='06'){
            $('#dropdownMenu1').text('C') 
        }
    }
      //获取app实际名称
      function getAppName(appid){
        if(appid=='02'){
            return 'A'
        }else if(appid=='05'){
            return 'B'
        }else if(appid=='06'){
            return 'C'
        }else {
            return appid
        }
    }
      //获取模拟接口url
      function getMockUrl(appid,reqid){
        if(appid=='02'){
            return '/msvr-lz/'+reqid
        }else if(appid=='05'){
            return '/msvr-zybb/'+reqid
        }else if(appid=='06'){
            return '/msvr-lzj/'+reqid
        }else {
            return '/msvr/'+reqid
        }
    }
      //生成每行数据         
      function getRow(element){
        var reqid = "'" + element.url + "'";
        var v = ''
        v=v+'<tr id ="'+element.id+'">'
        v=v+'<td class="th_item">'
        v=v+'<button type="button" class="btn btn-warning btn-xs" data-toggle="modal" data-target="#myModal-delete" onclick="clickDelBtn('+element.id+')" id="'+element.id+'">删除</button>'
        v=v+'<button type="button" class="btn btn-info btn-xs" data-toggle="modal" data-target="#myModal" onclick="setMockApi('+element.id+')" id="'+element.url+'">编辑</button>'
        v=v+'</td>'
        v=v+'<td>'
        v=v+'<pre>'
        v=v+getAppName(element.appid)
        v=v+'</pre>'
        v=v+'</td>'
        v=v+'<td class="th_taskid">'
        v=v+'<pre >'
        v=v+element.taskid
        v=v+'</pre>'
        v=v+'</td>'
        v=v+'<td>'
        v=v+'<pre>'
        v=v+getMockUrl(element.appid,element.url)
        v=v+'</pre>'
        v=v+'</td>'
        v=v+'<td class="th_long">'
        v=v+'<pre class=json-renderer id=json-renderer-'+element.id+'></pre>'
        v=v+'</td>'
        v=v+'</tr>'
        return v
      }
      //json格式化渲染出参区域
      function renderJsonView(element){
            var index = '#json-renderer-'+element.id
            $(index).jsonViewer(JSON.parse(element.resp));
      }
      //json数据格式转换
      function jsonShowFn(json){
        if (!json.match("^\{(.+:.+,*){1,}\}$")) {
            return json           //判断是否是json数据，不是直接返回
        }

        if (typeof json != 'string') {
            json = JSON.stringify(json, undefined, 2);
        }
        json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
        return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
            var cls = 'number';
            if (/^"/.test(match)) {
                if (/:$/.test(match)) {
                    cls = 'key';
                } else {
                    cls = 'string';
                }
            } else if (/true|false/.test(match)) {
                cls = 'boolean';
            } else if (/null/.test(match)) {
                cls = 'null';
            }
            return '<span class="' + cls + '">' + match + '</span>';
        });
    }
      //跳转查看模拟接口返回 
      function jumpMockApi(appid,reqid){
        if(appid='02'){
            window.location.href = '/msvr-lz/'+reqid
        }else if(appid=='06'){
            window.location.href = '/msvr-lzj/'+reqid
        }else if(appid=='05'){
            window.location.href = '/msvr-lzybb/'+reqid
        }
    }
      //设置编辑数据
      function setMockApi(id){
       $.ajax({
          type:"POST",
          url:'/mock/f4',
          data:{'id':id},
          success:function (resp) {
            _editInfo=resp.result
            $('#edit-body1').val(_editInfo.taskid)
            $('#edit-body2').val(_editInfo.url)
            $('#edit-body4').val(_editInfo.resp)
          },
          error:function(XMLHttpRequest,textStatus,errorThrown){
              console.log("jsonp.error:"+textStatus);
          }
      });
    }
      //执行编辑数据
      function editMock(){
        var taskid = $("#edit-body1").val();
        if(taskid.length==0){
            alert('taskid不能为空')
            return
        }
        var url =    $("#edit-body2").val();
        if(url.length==0){
            alert('reqid不能为空')
            return
        }

        var resp =   $("#edit-body4").val();
        if(resp.length==0){
            alert('resp不能为空')
            return
        }

        if(!isJSON(resp)){
            alert('resp is not json')
            return
        }

        $.ajax({
           type:"POST",
           url:'/mock/update',
           data:{
               'id':_editInfo.id,
               'url':url,
               'taskid':taskid,
               'req':url,
               'resp':resp,
           },
           success:function (resp) {
               
                $('#myModal').modal('hide')
                var  mockhistory =  $('#mockhistory')
                mockhistory.empty()
                getAllMockApis()
           },
           error:function(XMLHttpRequest,textStatus,errorThrown){
               console.log("jsonp.error:"+textStatus);
           }
       });
     }
      //删除模拟接口
      function clickDelBtn(reqid){
        _reqid = reqid
      }
      //删除模拟接口
      function delMockApi(){
        $.ajax({
            type:"POST",
            url:'/mock/f3',
            data:{'id':_reqid},
            success:function (arr) {
                $('#myModal-delete').modal('hide')
                $('#'+_reqid).remove()
            },
            error:function(XMLHttpRequest,textStatus,errorThrown){
                console.log("jsonp.error:"+textStatus);
            }
        });
      }
      //查询模拟卷接口
      function getAllMockApis(){
                $.ajax({
                        type:"POST",
                        url:'/mock/f1',
                        data:{'taskid':_taskid},
                        success:function (arr) {
                            var  mockhistory =  $('#mockhistory')
                            var arrIds = []
                            arr.forEach(element => {
                                mockhistory.append(getRow(element))
                                renderJsonView(element)
                            });
                        },
                        error:function(XMLHttpRequest,textStatus,errorThrown){
                            console.log("jsonp.error:"+textStatus);
                        }
                    });
        }
      //json格式校验
      function isJSON(str) {
            if(str.indexOf(":") == -1 ){
                return false
            }
            if (typeof str == 'string') {
                try {
                    var obj=JSON.parse(str);
                    console.log('转换成功：'+obj);
                    return true;
                } catch(e) {
                    console.log('error：'+str+'!!!'+e);
                    return false;
                }
            }
        }
      //新建模拟接口
      function addMockApi(){
        var appid =  _app;
        if(appid.length==0){
            alert('appid不能为空')
            return
        }
        var taskid = $("#body1").val();
        if(taskid.length==0){
            alert('taskid不能为空')
            return
        }
        var url =    $("#body2").val();
        if(url.length==0){
            alert('reqid不能为空')
            return
        }
        var req  = '{}'
  
        var resp =   $("#body4").val();
        if(resp.length==0){
            alert('resp不能为空')
            return
        }

        if(!isJSON(resp)){
            alert('resp is not json')
            return
        }

        $.ajax({
                        type:"POST",
                        url:'/mock/f2',
                        data:{'taskid':taskid,
                               'url':url,
                               'req':req,
                               'resp':resp,
                               'appid':appid
                             },
                        success:function (res) {
                            if(res.state!=0){
                                alert(res.msg)
                            }
                            var  mockhistory =  $('#mockhistory')
                            mockhistory.empty()
                            getAllMockApis()
                        },
                        error:function(XMLHttpRequest,textStatus,errorThrown){
                            alert('提交失败')
                        }
                    });
      }   
      //taskid搜索查询
      function taskSearchQuery( ){
         _taskid = $("#taskid_search").val()
         var  mockhistory =  $('#mockhistory')
         mockhistory.empty() 
         getAllMockApis()
      }
  
</script>

</html>